package com.itheima.aop;

import cn.hutool.json.JSONUtil;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;


@Slf4j
@Aspect
@Component
public class OperateLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    //第一种方式获取request请求
    @Autowired
    private HttpServletRequest request;
    @Around("@annotation(com.itheima.anno.Log)")
    //@Around("execution(* com.itheima.controller.*.*(..))")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        //第二种方式获取request请求
        /*HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes()).getRequest();*/

        String jwt = request.getHeader("token");
        Map<String, Object> map = JwtUtils.parseJwt(jwt);
        String userId = map.get("id").toString();


        OperateLog operateLog = new OperateLog();
        operateLog.setOperateUser(Integer.valueOf(userId));//操作人
        operateLog.setOperateTime(LocalDateTime.now());//操作时间
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());//操作的类名
        operateLog.setMethodName(joinPoint.getSignature().getName());//操作的方法名
        operateLog.setMethodParams(JSONUtil.toJsonStr(joinPoint.getArgs()));//操作的方法参数
        operateLog.setReturnValue(JSONUtil.toJsonStr(result));//操作的返回值
        operateLog.setCostTime(end - begin);//操作方法执行的耗时
        operateLogMapper.insert(operateLog);
        return result;
    }
}
